package com.september.util;
import java.lang.reflect.Method;

import com.google.code.morphia.Datastore;
import com.september.mongo.data.DataProvider;
import com.september.prop.Properteer;


public abstract class BaseData {
	public abstract String[] getOrdreredField();
	public abstract void manageRefernces();
	
	public static int nthOccurrence(String str, char c, int n) {
	    int pos = str.indexOf(c, 0);
	    while (n-- > 0 && pos != -1)
	        pos = str.indexOf(c, pos+1);
	    return pos;
	}
	
	public static String format(String input) {
		if (input.endsWith(".")) {
			return format(input.substring(0,input.length()-1));
		}
		else return input;
	}

	private static String parseField(String field, char separator) {
		if(field == null || field.trim().length() == 0) {
			return "";
		}
		else {
			return field+separator;
		}
	}
	
	public static String parseFields(char separator, String... fields) {
		String ret = "";
		for (String field: fields) {
			ret+= parseField(field, separator);
		}
		
		return format(ret);
	}
	
	protected Datastore getDs() {
		DataProvider provider = new DataProvider();
		return provider.getDatastore();
	}
	public  BaseData fromLine(String line, String[] order) {
		if(line.startsWith("#")) return null;
		//BaseData base = null;
		
		String[] splittedLine = line.split("\t");
		
		try {
			//base = new BaseData();
			for(int counter = 0; counter < order.length; counter ++) {
				if(splittedLine.length > counter) {
					Method setter = this.getClass().getMethod("set"+order[counter].substring(0, 1).toUpperCase()+order[counter].substring(1)
							, String.class);
					setter.invoke(this, splittedLine[counter]);
				}
			}
		}
		catch(Exception e) {
			Properteer.getInstance().getLogger(BaseData.class).error(e.getClass().getName(),e);
		}
		return this;
	}
}
